package com.dx.common.base.filter;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

//import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import com.dx.common.base.bean.CustomerBean;
import com.dx.common.base.core.LogManager;

/**
 * 
 * 用户操作日志过滤器
 * 
 * @author wKF52599
 * @version [NGESHOP V1.0, Nov 21, 2011]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
public class SystemLogFilter implements Filter
{
    
    private static final Logger logger = Logger.getLogger(SystemLogFilter.class);
    
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
            throws IOException, ServletException
    {
//    	try {
//			Thread.sleep(2000);
//		} catch (InterruptedException e1) {
//			// TODO Auto-generated catch block
//			e1.printStackTrace();
//		}
    	//System.out.println("SystemLogFilter start...");
        // 日志管理初始化
        LogManager.initialize();
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;
        HttpSession session = request.getSession();
        //设置channel_type
        String agent = request.getHeader("User-Agent");
        if(null != agent && "" != agent)
        {
            String channel_type = agent.toLowerCase();
            if((channel_type.indexOf("nokia")!=-1 || channel_type.indexOf("iphone")!=-1|| channel_type.indexOf("android")!=-1)) {
                LogManager.setChannel_type("WAP");
            }else{
                LogManager.setChannel_type("NET");
            }
        }
        else
        {
            LogManager.setChannel_type("NULL");
        }
        //设置action_url
        String requestUrl = request.getRequestURL().toString();
        requestUrl = requestUrl.split("//")[1];
        int startIdx = requestUrl.indexOf("/");
        int endIdx = requestUrl.indexOf("?")==-1?requestUrl.length():requestUrl.indexOf("?");
        String actionUrl = requestUrl.substring(startIdx, endIdx);
        //System.out.println(actionUrl);
        LogManager.setAction_url(actionUrl);
        LogManager.setAction_params(request.getParameterMap());
        // 获得用户信息
        LogManager.setSessionid(session.getId());
        CustomerBean customer = (CustomerBean)session.getAttribute("customer");
        if (customer != null)
        {
            LogManager.setCustomerBean(customer);
            
            //获取代理ip,array转发ip
            String proxyIp=getProxyIp(request);
            String forwardIp=getForwardIp(request);
            LogManager.setProxyIp(StringUtils.isBlank(proxyIp)?"":proxyIp);
            LogManager.setForwardIp(StringUtils.isBlank(forwardIp)?"":forwardIp);
            LogManager.setUserAgent(StringUtils.isBlank(agent)?"":agent);
            
            logger.info("当前用户已登录！");
        }
        else
        {
            LogManager.setVisitor(getIpAdd(request), "");
            
            //获取代理ip,array转发ip
            String proxyIp=getProxyIp(request);
            String forwardIp=getForwardIp(request);
            LogManager.setProxyIp(StringUtils.isBlank(proxyIp)?"":proxyIp);
            LogManager.setForwardIp(StringUtils.isBlank(forwardIp)?"":forwardIp);
            LogManager.setUserAgent(StringUtils.isBlank(agent)?"":agent);
            
            logger.info("当前用户未登录,为游客身份！");
        }
        //设置开始时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    	LogManager.setBiz_begindate(sdf.format(new Date()));
    	//System.out.println(sdf.format(new Date()));
    	//System.out.println("SystemLogFilter end!!!");
        chain.doFilter(request, response);
        
        //设置结束时间
        LogManager.setBiz_endate(sdf.format(new Date()));
        try
        {
            // 获取信息，放入 log
            LogManager.logging();
        }
        catch (Exception e)
        {
            e.printStackTrace();
            logger.error("Customer Operation Record Error !");
            logger.error(e);
        }
        finally
        {
            LogManager.destory();
        }
    }
    
    public void destroy()
    {
        LogManager.destory();

    }
    
    public void init(FilterConfig filterConfig)
    {

    }
    /**
     * 获取客户端IP地址
     * @return String 客户端IP地址
     */
    public static String getIpAdd(HttpServletRequest request)
    {
        String ip = request.getHeader("x-forwarded-for");
        //add begin yKF53986 2012/01/12 R003C11L12n01 
        //在反向代理 X-Forwarded-For中获取客户端真实的IP地址
        if (null != ip && 0 < ip.length() && !"unknown".equalsIgnoreCase(ip))
        {
            String[] ipArr = ip.split(",");
            for (int i = 0; i < ipArr.length; i++)
            {
                if (!"unknown".equalsIgnoreCase(ipArr[i]) && !"".equals(ipArr[i].trim()))
                {
                    ip = ipArr[i];
                    break;
                }
            }
        }
        //add begin yKF53986 2012/01/12 R003C11L12n01 
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
        {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
        {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
        {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
    
    /**
     * <一句话功能简述>获取代理ip
     * <功能详细描述>
     * @param request
     * @return
     * @see [类、类#方法、类#成员]
     */
    public static String getProxyIp(HttpServletRequest request)
    {
        String ip = request.getHeader("x-forwarded-for");
        return ip;
    }
    /**
     * <一句话功能简述>获取array转发ip
     * <功能详细描述>
     * @param request
     * @return
     * @see [类、类#方法、类#成员]
     */
    public static String getForwardIp(HttpServletRequest request)
    {
        String ip = request.getRemoteAddr();
        return ip;
    }
    
    
}
